﻿using Rj.PersonnelVerification.Server.Servers;


namespace Rj.PersonnelVerification.Server.Timeer.Impl
{
    public class TimedHostedService :  BackgroundService, IDisposable
    {
        private readonly IPersonVerficaService personVerficaService; // 注入服务

        private Timer _timer;

        private readonly IServiceScopeFactory _serviceScopeFactory; // 注入服务范围工厂


        public TimedHostedService(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;

            //var serviceScope =serviceScopeFactory.CreateScope();
            //personVerficaService = serviceScope.ServiceProvider.GetRequiredService<IPersonVerficaService>();
        }


        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(async state => await DoWork(), null, TimeSpan.Zero, TimeSpan.FromMinutes(20));
            return Task.CompletedTask;
        }

        private async Task DoWork()
        {
            //Console.WriteLine("定时任务正在执行: " + DateTime.Now);
            //await personVerficaService.DoWork();
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var personVerficaService = scope.ServiceProvider.GetRequiredService<IPersonVerficaService>();
                Console.WriteLine("定时任务正在执行: " + DateTime.Now);
                await personVerficaService.DoWork();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public override void Dispose()
        {
            _timer?.Dispose();
            base.Dispose();
        }

        protected override  Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //Console.WriteLine("定时任务正在执行: " + DateTime.Now);
            //await personVerficaService.DoWork();
            //StartAsync(stoppingToken);
            _timer = new Timer(async state => await DoWork(), null, TimeSpan.Zero, TimeSpan.FromMinutes(20));
            return Task.CompletedTask;
        }
    }
}
